package 二叉树;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode {
    int val = 0;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution1 {
    //https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
    public int[] preorderTraversal1 (TreeNode root) {
        //递归
        if (root == null) {
            return new int[0];
        }
        List<Integer> list = new ArrayList<>();
        list.add(root.val);
        int[] ret1 = preorderTraversal1(root.left);
        int[] ret2 = preorderTraversal1(root.right);
        for (int i:ret1) {//会对空解引用
            list.add(i);
        }
        for (int i:ret2) {
            list.add(i);
        }
        int[] ret = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ret[i] = list.get(i);
        }
        return ret;
    }
    public int[] preorderTraversal (TreeNode root) {
        //栈
        if (root == null) {
            return new int[0];
        }
        Stack<TreeNode> stack = new Stack<>();
        Stack<TreeNode> rep = new Stack<>();
        List<Integer> list = new ArrayList<>();
        stack.push(root);//null可以作为一个单位压入栈
        while (!stack.isEmpty()) {//里面有null内容的单位
            TreeNode curpeek = stack.peek();
            if (!rep.contains(curpeek)) {
                list.add(curpeek.val);
            }
            if (curpeek.left != null) {
                stack.push(curpeek.left);
                curpeek.left = null;
                rep.push(curpeek);
            }else {
                TreeNode curpop = stack.pop();
                if (curpop.right != null) {
                    stack.push(curpop.right);
                }
            }
        }
        int[] ret = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ret[i] = list.get(i);
        }
        return ret;
    }

    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node1.right = node2;
        node2.left = node3;
        solution1.preorderTraversal(null);
    }
}
